<script lang="ts" setup>
import api from '/@/api/email/index';
import AddRefund from './AddRefund.vue'
defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
})
const emit = defineEmits(['update:modelValue', 'refresh'])
const orderId = ref(undefined)
const showAddRefund = ref(false)
const AddRefundRef = ref()
const tableData = ref([]);
const close = () => {
    emit('update:modelValue', false)
}
const handleRefund = (row: any) => {
    showAddRefund.value = true
    AddRefundRef.value.ruleForm.orderId = row.id
    AddRefundRef.value.ruleForm.factoryId = row.factoryId
    AddRefundRef.value.currentMax = calcPaid(row.orderFactoryBillList, false)
}

const getInfo = async () => {
    const { data } = await api.order.info(String(orderId.value))
    if (data.orderFactoryList?.length) {
        const arrs = data.orderFactoryList.filter((f: { orderFactoryBillList: any[]; dataType: number; }) => f.orderFactoryBillList.findIndex((sf: { payStatus: number; }) => sf.payStatus === 1) > -1 && f.dataType === 1)
        if (arrs?.length) {
            arrs.forEach((e: { factoryInfo: string; }) => {
                e.factoryInfo = JSON.parse(e.factoryInfo)
            })
        }
        tableData.value = arrs
    }
}

function calcPaid(list: any[], isToFixed = true) {
  let amount = 0
  list.filter((f: { payStatus: number; }) => f.payStatus === 1).forEach((item: { goodsAmount: any; }) => {
    amount += item.goodsAmount || 0
  })
  return isToFixed ? amount.toFixed(3) : amount
}

defineExpose({
    orderId,
    getInfo,
})
</script>
<template>
    <TwoDialog id="RefundList" :modelValue="modelValue" title="退款列表" width="820px" :showConfirm="false" @close="close" @minimize="emit('update:modelValue', false)">
      <el-table :data="tableData" border empty-text="暂无可退款订单" style="width: 100%">
        <el-table-column prop="factoryInfo" label="工厂供应商">
            <template #default="{ row }">
                <div>{{ row.factoryInfo?.name }}</div>
            </template>
        </el-table-column>
        <el-table-column prop="factoryInfo" label="订单总金额(RMB)">
            <template #default="{ row }">
                <div>{{ row.billAmount?.toFixed(3) }}</div>
            </template>
        </el-table-column>
        <el-table-column prop="factoryInfo" label="已支付金额(RMB)">
            <template #default="{ row }">
                <div>{{ calcPaid(row.orderFactoryBillList) }}</div>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button plain type="primary" size="small" @click="handleRefund(row)">退款</el-button>
          </template>
        </el-table-column>
      </el-table>
        <AddRefund ref="AddRefundRef" v-model="showAddRefund" @refresh="getInfo" />
    </TwoDialog>
</template>
<style lang="scss" scoped>
.cascader-panel {
    width: fit-content;
}
</style>